const Koa = require('koa');
const app = new Koa();
const fs = require('fs');
const path = require('path');
// const view = require('koa-view');
const onerror = require('koa-onerror');
const koaBody = require('koa-body');
const logger = require('koa-logger');
const cors = require('@koa/cors');

const server = require('http').createServer(app.callback());
const servers = require('https').createServer({
  key: fs.readFileSync(path.join(__dirname, './certs/dev.key')), //ssl文件路径   第一步下载下来的证书文件
  cert: fs.readFileSync(path.join(__dirname, './certs/dev.pem')) //ssl文件路径
}, app.callback());

const index = require('./routes/index')

const port = 3001;

require('./config/db').sequelize.sync();

// error handler
onerror(app)

// middlewares
app.use(koaBody({
  multipart:true, // 支持文件上传
  formidable:{
    keepExtensions: true,    // 保持文件的后缀
    onFileBegin:(name,file) => { // 文件上传前的设置
      console.log(`name: ${name}`);
      console.log(`file: ${file}`);
      console.log(file.name);
      // PieceDirName = name.split('/')[0];
      // let RedirectPath = require('path').join(process.cwd(), './data/workpiece/' + PieceDirName);
      // require('./utils/FileOperate').checkDirExist(RedirectPath);
      // file.path = RedirectPath + '/' + file.name;
    },
  }
}));

app.use(cors());
app.use(logger());
app.use(require('koa-static')(__dirname + '/public'))
// app.use(require('koa-static')(require('path').join(process.cwd(), './data/workpiece')));
// app.use(view(__dirname + '/views', {ext: 'njk'}))

// logger
// app.use(async (ctx, next) => {
//     const start = new Date()
//     await next()
//     const ms = new Date() - start
//     console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
// })

// routes
app.use(index.routes(), index.allowedMethods())

app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
    // console.error(err.parent.sqlMessage);
});

server.listen(port, () => console.log('Listening on port 3001'));
servers.listen(443);

server.on('error', onError);

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
    if (error.syscall !== 'listen') {
        throw error;
    }

    let bind = typeof port === 'string'
        ? 'Pipe ' + port
        : 'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
        case 'EACCES':
            console.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;
        case 'EADDRINUSE':
            console.error(bind + ' is already in use');
            process.exit(1);
            break;
        default:
            throw error;
    }
}
